package com.hontech.bread.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.bread.R
import com.hontech.bread.device.Conn
import com.hontech.bread.ui.BaseActivity
import com.hontech.bread.ui.dialog.runProg
import com.hontech.bread.ui.dialog.runProgErr
import com.hontech.bread.ui.view.LabelSpinner
import com.hontech.bread.utils.AppTask
import com.hontech.bread.utils.onClick
import com.hontech.bread.utils.stringById

class SerialPortParts(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val spItems: LabelSpinner
    private val btnOpen: Button

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_serial_port, this)
        spItems = view.findViewById(R.id.id_serial_port_sp_ports)
        btnOpen = view.findViewById(R.id.id_serial_port_btn_open)

        btnOpen.onClick { onClickOpen() }

        view.findViewById<Button>(R.id.id_serial_port_btn_ping).onClick { onClickPing() }
        view.findViewById<Button>(R.id.id_serial_port_btn_exit)
            .onClick { BaseActivity.INSTANCE.finish() }

        AppTask.postDelayed({
            updateText()
        }, 3000)
    }

    private suspend fun onClickPing() {
        runProg("Ping", "Ping") {
            Conn.ping()
        }
    }

    private fun updateText() {
        if (Conn.isOpen()) {
            btnOpen.text = stringById(R.string.a2)
        } else {
            btnOpen.text = stringById(R.string.a2_)
        }
    }

    private suspend fun onClickOpen() {

        runProgErr(stringById(R.string.text_sp_ctrl)) {
            if (Conn.isOpen()) {
                Conn.close()
            } else {
                Conn.open(spItems.selectText())
            }
            updateText()
        }
    }
}


